package com.le.basic.StackAndQueue;
/**
 * 用数组结构实现大小固定的队列
 */
public class Code_02_ArrayToQueue {
    int[] queue;
    int start; // 出队
    int end; // 入队
    int size; //

    public Code_02_ArrayToQueue(int size) {
        queue = new int[size];
        this.size = 0;
        this.start = 0;
        this.end = 0;
    }

    public void push(int num){
        if (size == queue.length){
            throw new IndexOutOfBoundsException();
        }
        size++;
        queue[end] = num;
        end = (end == (queue.length - 1)) ? 0 : end + 1;
        if (end == 0){
            size--;
        }
    }

    public int pop(){
        if (size == -1){
            throw new IndexOutOfBoundsException();
        }
        size--;
        int temp = start;
        start = start == queue.length - 1 ? 0 : start + 1;
        return queue[temp];
    }

    public int peek(){
        if (size ==0){
            return -1;
        }
        return queue[start];
    }

    public static void main(String[] args) {
        Code_02_ArrayToQueue queue = new Code_02_ArrayToQueue(3);
        queue.push(1);
        queue.push(2);
        queue.push(3);
        System.out.println(queue.pop());
        System.out.println("**********");
        queue.push(4);
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
//        System.out.println(queue.pop());
        queue.push(5);
        System.out.println(queue.size);
        System.out.println(queue.pop());
    }
}
